# -*- coding: utf-8 -*-
# !/usr/bin/env python
import uuid

from rest_framework.views import APIView
from components.models import AppsConfiguration
from components.resource_management.app_conf.dao import query_app_info
from components.resource_management.soft_manage.dao import update_install_conf, post_install_conf, get_install_conf
from utils.views import Result

class AppConf(APIView):
    def get(self, request):
        data = request.query_params
        app_dict = {}
        if data['app_id']:
            app_dict['app_form'] = query_app_info(data['app_id'])
        if app_dict['app_form']['conf_manage_ids']:
            app_dict['install_conf'] = get_install_conf(app_dict['app_form']['conf_manage_ids'])

        return Result.success_response(data=app_dict, msg='查询成功')

    def post(self, request):
        data = request.data
        app_form = data['app_form']
        # if 'host_id' in data: data.pop('host_id')
        app_form['status'] = 1
        conf_manage_ids = str(uuid.uuid1())
        app_form['conf_manage_ids'] = conf_manage_ids

        try:
            post_install_conf(data['install_conf'], app_form['conf_manage_ids'])
            save_data = AppsConfiguration(**app_form)
            save_data.save()
        except Exception as e:
            return Result.fail_response(msg=str(e))

        return Result.success_response(msg='保存成功')


    def put(self, request):
        data_dict = request.data.copy()

        data = data_dict['app_form']

        AppsConfiguration.objects.filter(app_id=data['app_id']).update(
            host_id=data['host_id'],
            app_nick=data['app_nick'],
            package_id=data['package_id'],
            app_deploy_code=data['app_deploy_code'],
            app_log_path=data['app_log_path'],
            app_restart_cmd=data['app_restart_cmd'],
            app_start_cmd=data['app_start_cmd'],
            app_stop_cmd=data['app_stop_cmd'],
            app_check_code=data['app_check_code'],
            app_check_url=data['app_check_url'],
            status=data['status'],
            comment=data['comment']
        )

        update_install_conf(data_dict['install_conf'])

        return Result.success_response(msg='修改成功')


    def delete(self, request):
        data = request.data
        app_ids = data['app_ids']

        AppsConfiguration.objects.filter(app_id__in=app_ids).update(status=0)

        return Result.success_response(msg='删除成功')